package com.adroit.hsweb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HSMainServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3741907266425098699L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
		
		String actionParam = request.getParameter("action");
		PrintWriter pw = response.getWriter();
		
		if(actionParam != null && actionParam.length() > 0) {
			response.setContentType("application/json");
			processAPIAction(actionParam, pw);
		} else {
//			response.setContentType("text/xml");
//			showErrorXML(pw);
			
			response.setContentType("application/json");
			processAPIAction(actionParam, pw);
		}
		pw.close();
	}
	
	private void processAPIAction(String action, PrintWriter pw) {
		
		Map<String, Object> outerMap = new LinkedHashMap<String, Object>();    
	    outerMap.put("server", "tcb-tomcat");	
	    outerMap.put("api-version", "Not Implemented");
	    outerMap.put("action", action);
	    outerMap.put("user-auth", "false");
	    outerMap.put("user-session", "false");
	    outerMap.put("result-set-count", "0");
	    
	    JSONObject jsonObject = null; 
	    
		if("getPlaylist".equals(action)) {
			outerMap.put("api-version", "1.0");
			outerMap.put("result-set-count", "10");
			
		    ArrayList< HashMap<String, String> > innerMapArray = new ArrayList< HashMap<String, String> >(); 
		    		
		    for(int i=0; i<5; i++) {
		    	HashMap<String, String> innerMap = new HashMap<String, String>();
		    	innerMap.put("Title", "title-"+(i+1));
		    	innerMap.put("Artist", "artist-"+(i+1));
		    	innerMap.put("Album", "album-"+(i+1));
		    	innerMap.put("Uri", "http://thecodebreakers.com/hsweb/songs/"+ "title-" + (i+1) + ".mp3");
		    	innerMapArray.add(innerMap);
		    }
		    
			JSONArray jsonArray = JSONArray.fromObject(innerMapArray);
			outerMap.put("data-array", jsonArray);
			
		} else {
			
		}
		jsonObject = JSONObject.fromObject(outerMap);
		pw.println(jsonObject.toString());
	}
	
	private void showErrorXML(PrintWriter pw) {
		
//	    StringTokenizer str = new StringTokenizer("<?xml version="1.0" encoding="iso-8859-1"?/>");
	    pw.println("<root>");
	    pw.println("<body>");
	    pw.println("<message>");
	  
	    
		pw.println("</body></root>");
	}
}
